﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows;

namespace TestApp
{
    public class MainWindowViewModel
    {
        private Point _startPoint = new Point(0, 0);
        private bool _isMoving = false;
        public void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!_isMoving)
            {
                _isMoving = true;
                _startPoint = e.GetPosition((IInputElement)sender);
                Mouse.Capture((IInputElement)sender);
            }
        }

        public void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Mouse.Capture(null);
            _isMoving = false;
        }

        public void OnMouseMove(object sender, MouseEventArgs e)
        {
            if (_isMoving)
            {
                var p = e.GetPosition(GetParentCanvas(sender));
                var target = sender as FrameworkElement;
                Canvas.SetLeft(target, p.X - _startPoint.X);
                Canvas.SetTop(target, p.Y - _startPoint.Y);
            }
        }

        private Canvas GetParentCanvas(object obj)
        {
            var parent = VisualTreeHelper.GetParent((DependencyObject)obj);
            if (parent != null && parent is Canvas)
                return (Canvas)parent;
            return GetParentCanvas(parent!);
        }
    }
}
